package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 通过编写定制的ThreadFactory可以定制由Executor创建的线程的属性（后台、优先级、名称）
 *
 * 2018年 09月 23日 星期日
 * @author fireway
 */
public class DaemonFromFactory implements Runnable {
    private static final boolean DEBUG = true;

    @Override
    public void run() {
        try {
            while (true) {
                TimeUnit.MILLISECONDS.sleep(100);
                if (DEBUG) {
                    System.out.println(Thread.currentThread()
                                       + ", current thread["
                                       + System.identityHashCode(Thread.currentThread()) + "]");
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new DaemonThreadFactory());
        for (int i = 0; i < 10; i++) {
            Runnable r = new DaemonFromFactory();
            if (DEBUG) {
                System.out.println("main() r[" + System.identityHashCode(r) + "]");
            }
            exec.execute(r);
        }

        System.out.println("All daemon started");
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        exec.shutdown();
    }
}
